package com.cs.study.homework._0314.queue;


//队列的顺序存储 --->底层使用循环数组
public class MyArrayQueue<E> {

    // 基本结构
    // 初始大小
    private static int INIT_CAPACITY = 5;

    // 队头
    private int front;
    //队尾
    private int rear;
    //数组
    private Object[] values;
    //队列大小
    private int size;

    public MyArrayQueue() {
        values = new Object[INIT_CAPACITY];
    }

    public int size() {
        return size;
    }

    public boolean isFull() {
        return size == values.length;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    //入队操作
    public boolean offer(E value) {
        if (isFull()) {
            grow();
        }
        values[size] = value;
        size++;
        return true;

    }

    public void grow() {
        Object[] newArray = new Object[values.length << 1];
        System.arraycopy(values, 0, newArray, 0, values.length);
        values = newArray;
    }

    //出队操作
    public E pop() {
        if (isEmpty()) {
            throw new RuntimeException("queue is empty");
        }
        // 队列中只有1个元素
        // 出队后重置队头队尾
        if (size == 1) {
            E value = (E) values[front];
            values[front] = null;
            front = 0;
            rear = 0;
            size--;
            return value;
        }
        E value = (E) values[front];
        values[front] = null;
        front = (front + 1) % values.length;
        size--;
        return value;

    }
}
